package com.zzy.customglide;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;

import com.zzy.customglide.manager.ActivityFragmentManager;
import com.zzy.customglide.manager.FragmentActivityFragmentManager;
import com.zzy.customglide.manager.LoadEngine;

public class RequestManager {
    private static final String TAG = RequestManager.class.getSimpleName();
    private Context requestMangerContext;
    private final  String FRAGMENT_ACTIVITY_NAME="Z_NAME";
    private final  String ACTIVITY_NAME="Z_NAME_ACTIVITY";
    private final int NEXT_HANDLER_MSG = 544;
    FragmentActivity fragmentActivity;
    private static LoadEngine requestTargetEngine;
    {
        if (requestTargetEngine == null) {
            requestTargetEngine = new LoadEngine();
        }
    }


    public RequestManager(FragmentActivity fragmentActivity){
        this.requestMangerContext=fragmentActivity;
        this.fragmentActivity=fragmentActivity;
        FragmentManager fragmentManager=fragmentActivity.getSupportFragmentManager();
       Fragment fragment= fragmentManager.findFragmentByTag(FRAGMENT_ACTIVITY_NAME);
        //添加一个空的Fragment来控制生命周期
       if(null==fragment){
           fragment =new FragmentActivityFragmentManager(requestTargetEngine);
           fragmentManager.beginTransaction().add(fragment,FRAGMENT_ACTIVITY_NAME).commitAllowingStateLoss();
       }
        mHandler.sendEmptyMessage(NEXT_HANDLER_MSG);



    }
    public RequestManager(Activity activity){
        this.requestMangerContext=activity;
        android.app.FragmentManager fragmentManager=activity.getFragmentManager();
        android.app.Fragment fragment= fragmentManager.findFragmentByTag(ACTIVITY_NAME);
        //添加一个空的Fragment来控制生命周期
        if(null==fragment){
            fragment =new ActivityFragmentManager(requestTargetEngine);
            fragmentManager.beginTransaction().add(fragment,ACTIVITY_NAME).commitAllowingStateLoss();
        }

    }



    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Log.i("handleMessage:","msg");
            Fragment fragment2 = fragmentActivity.getSupportFragmentManager().findFragmentByTag(FRAGMENT_ACTIVITY_NAME);
            Log.d(TAG, "Handler: fragment2" + fragment2);
            return false;
        }
    });
    /**
     * 无法管理生命周期
     * @param mContext
     */
    public RequestManager(Context mContext){
        this.requestMangerContext=mContext;
    }


    public LoadEngine load(String url){
//        mHandler.removeMessages(NEXT_HANDLER_MSG);
        requestTargetEngine.loadValue(url,requestMangerContext);
        return requestTargetEngine;
    }


}
